package tech.topcoder.springcloud.simpleservice.service.impl;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import tech.topcoder.springcloud.simpleservice.bean.Demo;
import tech.topcoder.springcloud.simpleservice.bean.DemoExample;
import tech.topcoder.springcloud.simpleservice.dao.DemoDao;
import tech.topcoder.springcloud.simpleservice.mybatis.Page;
import tech.topcoder.springcloud.simpleservice.mybatis.Pagination;
import tech.topcoder.springcloud.simpleservice.service.DemoService;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @author hhj
 */
@Service
public class DemoServiceImpl implements DemoService {

    @Resource
    private DemoDao demoDao;

    public Pagination<Demo> getPageList(Integer start, Integer length, String keyword) {
        Page page = new Page(start, length);

        DemoExample example = new DemoExample();
        example.setOrderByClause("addtime desc");
        if (StringUtils.isNotBlank(keyword)) {
            example.createCriteria().andTitleLike("%" + keyword + "%");
        }
        example.setPage(page);

        long total = demoDao.countByExample(example);

        return new Pagination<Demo>(total, demoDao.selectByExample(example));
    }

    public int add(Demo record) {
        if (record.getAddtime() == null) {
            record.setAddtime(new Date());
        }
        return demoDao.insertSelective(record);
    }

    @Override
    public Demo getById(int id) {
        return demoDao.selectByPrimaryKey(id);
    }
}
